package serviceimpl

import (
	"github.com/RaymondCode/simple-demo/entity/bo"
	"github.com/RaymondCode/simple-demo/entity/param"
	"github.com/RaymondCode/simple-demo/entity/po"
	"github.com/RaymondCode/simple-demo/repository/impl"
	"github.com/RaymondCode/simple-demo/service"
	"github.com/RaymondCode/simple-demo/util/entityutil"
	"github.com/RaymondCode/simple-demo/util/rabbitutil"
	"sync"
)

type Relation struct {
}

func (r Relation) Follow(relationParam *param.Relation, userId int) error {
	err := rabbitutil.Follow(userId, relationParam.ToUserID, relationParam.ActionType == param.DO_FOLLOW)
	if err != nil {
		return err
	}
	return nil
}

func (r Relation) FollowList(userId int) (*[]bo.User, error) {
	var userPOS *[]po.User
	userPOS, err := impl.NewUserDaoInstance().QueryFollows(userId)
	if err != nil {
		return nil, err
	}
	var userBOS = make([]bo.User, len(*userPOS))
	err = entityutil.GetUserBOS(userPOS, &userBOS)
	for i := range userBOS {
		fansFans, err := impl.NewRelationDaoInstance().QueryFollowIdByFansId(userBOS[i].ID)
		if err != nil {
			return nil, err
		}
		for _, fansFanId := range fansFans {
			if fansFanId == userId {
				userBOS[i].IsFollow = true
				break
			}
		}
	}
	if err != nil {
		return nil, err
	}
	return &userBOS, nil
}

func (r Relation) FansList(userId int) (*[]bo.User, error) {
	var userPOS *[]po.User
	userPOS, err := impl.NewUserDaoInstance().QueryFans(userId)
	if err != nil {
		return nil, err
	}
	var userBOS = make([]bo.User, len(*userPOS))
	err = entityutil.GetUserBOS(userPOS, &userBOS)
	for i := range userBOS {
		fansFollows, err := impl.NewRelationDaoInstance().QueryFollowIdByFansId(userBOS[i].ID)
		if err != nil {
			return nil, err
		}
		for _, fansFollowId := range fansFollows {
			if fansFollowId == userId {
				userBOS[i].IsFollow = true
				break
			}
		}
	}
	if err != nil {
		return nil, err
	}
	return &userBOS, nil
}

// FriendList 查看好友列表
func (r Relation) FriendList(userId int) (*[]bo.User, error){
	// 查询粉丝
	var userPOS *[]po.User
	userPOS, err := impl.NewUserDaoInstance().QueryFans(userId)
	if err != nil {
		return nil, err
	}
	var userBOS = make([]bo.User, len(*userPOS))
	err = entityutil.GetUserBOS(userPOS, &userBOS)
	if err != nil{
		return nil, err
	}
	var friendBOS = make([]bo.User, 0)
	idx := 0
	for i := range userBOS{
		// 查询每个粉丝的关注列表，互相匹配就是好友
		fansFollows, err := impl.NewRelationDaoInstance().QueryFollowIdByFansId(userBOS[i].ID)
		if err != nil {
			return nil, err
		}
		for _, fansFollowId := range fansFollows {
			if fansFollowId == userId {
				friendBOS = append(friendBOS, userBOS[i])
				friendBOS[idx].IsFollow = true
				idx++
				break
			}
		}
	}
	return &friendBOS, nil
}

var (
	relation     service.Relation
	relationOnce sync.Once
)

func NewRelationServiceInstance() service.Relation {
	relationOnce.Do(func() {
		relation = Relation{}
	})
	return relation
}
